import express from 'express';
import multer from 'multer';
import path from 'path';
import { Attachment, Card } from '../lib/models';
import { authMiddleware } from '../middlewares/auth';
import { io } from '../startup/socket';

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'uploads/');
  },
  filename: (req, file, cb) => {
    const uniqueSuffix = `${Date.now()}-${Math.round(Math.random() * 1E9)}`;
    cb(null, `${file.fieldname}-${uniqueSuffix}${path.extname(file.originalname)}`);
  }
});

const upload = multer({ 
  storage,
  limits: {
    fileSize: 5 * 1024 * 1024 // 5MB
  },
  fileFilter: (req, file, cb) => {
    const allowedTypes = /jpeg|jpg|png|gif|pdf|doc|docx|xls|xlsx/;
    const extname = allowedTypes.test(path.extname(file.originalname).toLowerCase());
    const mimetype = allowedTypes.test(file.mimetype);
    
    if (extname && mimetype) {
      return cb(null, true);
    }
    cb(new Error('不支持的文件类型'));
  }
});

const router = express.Router();
router.use(authMiddleware);

router.post('/:cardId', upload.single('file'), async (req, res) => {
  try {
    const card = await Card.findById(req.params.cardId);
    if (!card) {
      return res.status(404).json({ error: '卡片不存在' });
    }

    const attachment = new Attachment({
      filename: req.file.originalname,
      path: req.file.path,
      size: req.file.size,
      mimetype: req.file.mimetype,
      cardId: card._id,
      userId: req.userId
    });

    await attachment.save();
    
    card.attachments.push(attachment._id);
    await card.save();
    
    io.to(card.boardId.toString()).emit('card:update', card);
    
    res.json(attachment);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

export default router; 